package com.world.cat.service.sys;

import com.world.cat.dao.sys.ConfigDao;
import com.world.cat.model.sys.Config;
import com.world.common.pojo.Result;
import com.world.common.util.CollectionUtil;
import com.world.common.util.SysUtil;
import com.world.core.dao.GenericRepository;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by gang on 2017/3/14.
 */
@Service
@Transactional
public class ConfigService extends BaseService<Config> {
    private static final Logger logger = Logger.getLogger(ConfigService.class);
    public static Map<String, Config> configMap = new ConcurrentHashMap<>();

    @Resource
    private ConfigDao configDao;

    @Override
    public GenericRepository getDao() {
        return configDao;
    }

    public void initConfigCache() {
        logger.info("初始化配置数据开始--------------------------------");
        List<Config> os = configDao.findAll();
        if (CollectionUtil.isNotEmpty(os)) {
            for (Config o : os) {
                ConfigService.configMap.put(o.getConfigKey(), o);
            }
        }
        logger.info("初始化配置数据结束--------------------------------");
    }

    public Result saveParam(String configKey, String configValue) throws Exception {
        if (SysUtil.isEmpty(configKey)) {
            return new Result(false, "参数为空");
        }
        if (SysUtil.isEmpty(configValue)) {
            return new Result(false, "参数值为空");
        }
        Config config = configDao.findByConfigKey(configKey);
        if (config != null) {
            config.setConfigValue(configValue);
        } else {
            logger.info("参数不存在，默认将该参数加入到数据库中");
            //此处默认把参数加到数据库中，便于后面的配置
            config = new Config(configKey, configValue, "", "");
            configDao.save(config);
        }
        configMap.put(configKey, config);
        return new Result(true, "设置成功");
    }
}
